<?php
session_start();
$lib_dir = str_ireplace("ajax", "lib", dirname(__FILE__));
require_once $lib_dir.'/config.php';
require_once $lib_dir.'/facebook.php';
require_once $lib_dir.'/util.php';
require_once $lib_dir.'/friend.php';
require_once $lib_dir.'/friends.php';

if(!isset($_SESSION['fb_'.FB_APP_ID.'_access_token'])){
    print('{ "error": "not connected to Facebook" }');
    exit();
}

//if graph data is already loaded
if(isset($_SESSION['friends'])){
    print($_SESSION['friends']);
} else {

    $facebook = new Facebook(array(
        'appId' => FB_APP_ID,
        'secret' => FB_APP_SECRET
    ));
    
    $user = $facebook->getUser();
    
    $friends = null;
    if($user){
        try{
            $now = time();	
        	
            $friends = getFriends();
            
            //JSON encoding
            $json = '{';
            $json .= '"type": "friend",';
            $json .= '"data": [';
        
            $isFirst = true;
            foreach($friends as $f){
                if(!$isFirst){
                    $json .= ',';
                }
                $json .= '{';
                $json .= '"fId" : "'.$f->getfId().'",';
                $json .= '"name" : "'.$f->getName().'"';
                $json .= '}';
                $isFirst = false;
            }
        
            $json .= ']';
            $json .= '}';
    
            $_SESSION['friends'] = $json;
            
            //return output
            print $json;


			$log = "Hashed UID:".md5($_SESSION['fb_session']['uid']).",Number of Friends:".count($friends).",Elapsed Time:".(time() - $now)."\n";
			writeToLogfile($log);

           
        } catch (FacebookApiException $e){

            print('{"error":"'."Facebook error:".$e->getMessage().'"}');
        }
    }
}
